import streamlit as st
import requests
from PIL import Image
import io
import json
import sys
import requests

def send_request(uploaded_file):

    # 准备文件和参数
    files = {
        'file': uploaded_file
    }
    data = {
    }

    # 发送请求
    response = requests.post('http://localhost:5000/api/analyze', 
                            files=files,
                            data=data)

    # 打印结果
    print(response.json())
    return response.json()

def main():
    st.set_page_config(
        page_title="Benetech - Making Graphs Accessible",
        page_icon="📊",
        layout="wide"
    )

    st.title("Benetech - Making Graphs Accessible")
    st.write("上传图表图片，获取详细分析结果")

    # 文件上传
    uploaded_file = st.file_uploader(
        "选择图片文件",
        type=["jpg", "jpeg", "png", "gif"],
        help="支持的格式：JPG、PNG、GIF"
    )

    if uploaded_file is not None:
        # 显示上传的图片
        image = Image.open(uploaded_file)
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("上传的图片")
            st.image(image, use_column_width=True)

        # 处理按钮
        if st.button("开始分析", type="primary"):
            with st.spinner("正在处理中..."):
                try:
                    # 这里替换为实际的API调用
                    # response = requests.post(
                    #     "YOUR_API_ENDPOINT",
                    #     files={"image": uploaded_file}
                    # )
                    # result = response.json()

                    # 临时示例结果
                    # result = {
                    #     "status": "success",
                    #     "message": "图片处理完成",
                    #     "data": {
                    #         "type": "line_graph",
                    #         "title": "示例图表",
                    #         "description": "这是一个示例分析结果"
                    #     }
                    # }
                    result = send_request(uploaded_file)
                    with col2:
                        st.subheader("分析结果")
                        st.json(result)

                except Exception as e:
                    st.error(f"处理出错: {e}")

    # 使用说明
    with st.expander("使用说明"):
        st.markdown("""
        ### 使用步骤
        1. 点击"选择图片文件"或将文件拖放到上传区域
        2. 等待图片预览加载完成
        3. 点击"开始分析"按钮
        4. 查看分析结果

        ### 注意事项
        - 请确保上传清晰的图表图片
        - 支持的文件格式：JPG、PNG、GIF
        - 建议图片大小不超过5MB
        """)

if __name__ == "__main__":
    main()
